package com.sftz.modules.minapp.myhomework.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.Param;

import com.sftz.assets.entities.question.HomeworkAnswerInfoEntity;
import com.sftz.assets.enums.StateOrTimeEnum;
import com.sftz.modules.minapp.myhomework.dto.MyHomeworkDto;
import com.sftz.modules.minapp.myhomework.form.MyHomeworkShowForm;
import com.sftz.modules.minapp.resourceRecord.dto.PersonCourseScoreDto;
import com.sftz.modules.minapp.resourceRecord.service.StudentOtherCourseScoreViewService;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.util.DbSqlUtil;
import com.uxuexi.core.web.base.service.BaseService;

@IocBean
public class MyHomeworkViewService extends BaseService<HomeworkAnswerInfoEntity> {
	private static final Log log = Logs.get();

	@Inject
	private StudentOtherCourseScoreViewService studentOtherCourseScoreViewService;

	private static final int willdate = 1;//将过期

	private static final int yetdate = 0;//全部

	/**
	 * 
	 * @author   郝振斌
	 * @Date	 2018年12月18日
	 *（用途:我的作业）
	 */
	public Object list(String token, Integer courseId, MyHomeworkShowForm myHomeworkShowForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer userId = RedissionUserCache.getUserId(token);
		if (userId == null) {
			return null;
		} else {
			//当前学院Id
			Cnd cnd = Cnd.NEW();
			List<MyHomeworkDto> myHomework = new ArrayList<MyHomeworkDto>();

			Integer courseStatus = myHomeworkShowForm.getCourseStatus();
			if (courseStatus == StateOrTimeEnum.ALLSTA.intKey()) {//全部
				//已审批-未审批
				myHomework = corretOrNotmyList(userId, courseId, myHomeworkShowForm);
				//将过期
				List<MyHomeworkDto> willDatedList = willDatedList(userId, courseId, myHomeworkShowForm);
				//已过期
				List<MyHomeworkDto> datedList = datedList(userId, courseId, myHomeworkShowForm);
				myHomework.addAll(willDatedList);
				myHomework.addAll(datedList);
			} else if (courseStatus == StateOrTimeEnum.WILLDATED.intKey()) {//将过期
				myHomework = willDatedList(userId, courseId, myHomeworkShowForm);
			} else if (courseStatus == StateOrTimeEnum.DATED.intKey()) {//已过期
				myHomework = datedList(userId, courseId, myHomeworkShowForm);
			} else {
				//已审批-未审批
				myHomework = corretOrNotmyList(userId, courseId, myHomeworkShowForm);

			}
			obj.put("myHomework", myHomework);
			return obj;
		}
	}

	/**
	 * 查询未审批/已审批数据
	 * @param userId
	 * @param courseId
	 * @param myHomeworkShowForm
	 * @return
	 */
	private List<MyHomeworkDto> corretOrNotmyList(Integer userId, Integer courseId,
			MyHomeworkShowForm myHomeworkShowForm) {
		Cnd cnd = Cnd.NEW();
		Integer courseStatus = myHomeworkShowForm.getCourseStatus();
		Sql studentS = Sqls.create(sqlManager.get("minapp_my_center_homework_list"));
		if (courseStatus == StateOrTimeEnum.UNAPPROVED.intKey() || courseStatus == StateOrTimeEnum.APPROVED.intKey()) {
			cnd.and("hi.status", "=", myHomeworkShowForm.getCourseStatus());
			cnd.and("hi.studentId", "=", userId);
			cnd.and("h.courseId", "=", courseId);
			studentS.setCondition(cnd);
		} else if (courseStatus == StateOrTimeEnum.ALLSTA.intKey()) {
			SqlExpressionGroup group2 = new SqlExpressionGroup();
			group2.and("hi.status", "=", StateOrTimeEnum.UNAPPROVED.intKey()).or("hi.status", "=",
					StateOrTimeEnum.APPROVED.intKey());
			cnd.and(group2);
			cnd.and("hi.studentId", "=", userId);
			cnd.and("h.courseId", "=", courseId);
			studentS.setCondition(cnd);
		}
		List<MyHomeworkDto> myHomework = DbSqlUtil.query(dbDao, MyHomeworkDto.class, studentS);
		return myHomework;
	}

	/**
	 * 查询将过期数据
	 * @param userId
	 * @param courseId
	 * @param myHomeworkShowForm
	 * @return
	 */
	private List<MyHomeworkDto> willDatedList(Integer userId, Integer courseId, MyHomeworkShowForm myHomeworkShowForm) {
		Cnd cnd = Cnd.NEW();
		Sql datedHomeSq = Sqls.create(sqlManager.get("minapp_my_center_homework_datedHomeSq"));
		datedHomeSq.setParam("userId", userId);
		String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		Calendar calendar = Calendar.getInstance();
		calendar.add(calendar.HOUR, 48);
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
		SqlExpressionGroup group = new SqlExpressionGroup();
		group.andBetween("endTime", dateNow, date).orBetween("postDate", dateNow, date);
		cnd.and(group);
		cnd.and("courseId", "=", courseId);
		datedHomeSq.setCondition(cnd);
		List<MyHomeworkDto> myHomework = DbSqlUtil.query(dbDao, MyHomeworkDto.class, datedHomeSq);
		for (MyHomeworkDto myHomeworkDto : myHomework) {
			myHomeworkDto.setStatus(StateOrTimeEnum.WILLDATED.intKey());
		}
		return myHomework;

	}

	/**
	 * 查询已过期数据
	 * @param userId
	 * @param courseId
	 * @param myHomeworkShowForm
	 * @return
	 */
	private List<MyHomeworkDto> datedList(Integer userId, Integer courseId, MyHomeworkShowForm myHomeworkShowForm) {
		Cnd cnd = Cnd.NEW();
		Sql datedHomeSq = Sqls.create(sqlManager.get("minapp_my_center_homework_datedHomeSq"));
		datedHomeSq.setParam("userId", userId);
		String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		cnd.and("endTime", "<", dateNow);
		cnd.and("courseId", "=", courseId);
		datedHomeSq.setCondition(cnd);
		List<MyHomeworkDto> myHomework = DbSqlUtil.query(dbDao, MyHomeworkDto.class, datedHomeSq);
		for (MyHomeworkDto myHomeworkDto : myHomework) {
			myHomeworkDto.setStatus(StateOrTimeEnum.DATED.intKey());
		}
		return myHomework;
	}

	//（用途:我的作业记录进度查询）
	public PersonCourseScoreDto myWorkProcessData(@Param("userId") final Integer userId,
			@Param("courseId") final Integer courseId) {
		return studentOtherCourseScoreViewService.findStudentScore(courseId, userId);
	}

	public Object initData(String token, Integer courseId, MyHomeworkShowForm myHomeShowForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer userId = RedissionUserCache.getUserId(token);
		//当前学院Id
		Cnd cnd = Cnd.NEW();
		List<MyHomeworkDto> myHomework = new ArrayList<MyHomeworkDto>();

		//将过期
		myHomework = willDatedList(userId, courseId, myHomeShowForm);
		if (!Util.isEmpty(myHomework)) {
			obj.put("myHomework", myHomework);
			obj.put("activeType", willdate);
		} else {
			//已审批-未审批
			myHomework = corretOrNotmyList(userId, courseId, myHomeShowForm);
			//将过期
			List<MyHomeworkDto> willDatedList = willDatedList(userId, courseId, myHomeShowForm);
			//已过期
			List<MyHomeworkDto> datedList = datedList(userId, courseId, myHomeShowForm);
			myHomework.addAll(willDatedList);
			myHomework.addAll(datedList);
			obj.put("myHomework", myHomework);
			obj.put("activeType", yetdate);
		}
		return obj;
	}

}